#!/usr/bin/env bash

# 以下是两个教程. 不过第一个已经 404 了.
# - [教程](https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-20-04)
# - [教程](https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-16-04)

# Step 1.
# 需要编译几个平台的版本的话, 使用下面的命令, 在展示出来的列表找
# 然后添加到下方的 `platforms` 里去..
# $> go tool dist list

# Step 2.
# how to build
# chmod +x go-executable-build.sh
# need `Fullpath`
# $> ./go-executable-build.sh /Users/mac/xunso


package=$1
if [[ -z "$package" ]]; then
  echo "usage: $0 <package-name>"
  exit 1
fi
package_split=(${package//\// })
package_name=${package_split[-1]}

# 这里编译了 4 个平台的代码.
# 新增了 arm64 针对的是 M1 的 Mac 电脑
platforms=(
  "linux/386"
  "linux/amd64"
  "windows/amd64"
  "darwin/amd64"
  "darwin/arm64"
)

for platform in "${platforms[@]}"
do
	# 下面这几句只是拼接最后的build 出来的名字而已.
    platform_split=(${platform//\// })
    GOOS=${platform_split[0]}
    GOARCH=${platform_split[1]}
    output_name=$package_name'-'$GOOS'-'$GOARCH

    if [ $GOOS = "windows" ]; then
        output_name+='.exe'
    fi    

	# 打印错误.
    env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
    if [ $? -ne 0 ]; then
           echo 'An error has occurred! Aborting the script execution...'
        exit 1
    fi
done

